package com.yape.webCrawler.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yape.po.StockNews;
import com.yape.webCrawler.base.BaseCrawler;
import com.yape.webCrawler.util.JsonUtils;
import com.yape.annotation.CrawlerLog;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Hazuki
 * @Date 2025/5/23 合并快讯爬虫
 * @Version 1.0
 */
@Slf4j
@Component("fastNews")
public class FastNewsCrawler extends BaseCrawler {
    private static final String COUNT_URL_TEMPLATE =
            "https://np-weblist.eastmoney.com/comm/web/getFastNewsCount?client=web&biz=web_724&fastColumn=102%s&req_trace=%d&_=%d&callback=jQuery123456_%s";
    private static final String NEWS_URL_TEMPLATE =
            "https://np-weblist.eastmoney.com/comm/web/getFastNewsList?client=web&biz=web_724&fastColumn=102&sortEnd=&pageSize=%d&req_trace=%d";
    private static final String URL_ = "https://finance.eastmoney.com/a/";
    private static final String END = ".html";



    @CrawlerLog
    @Override
    public List<StockNews> execute() throws IOException {
        long currentReqTrace = System.currentTimeMillis();
        // 1. 获取当天0点时间戳
        String sortStart = String.valueOf(getTodayMidnightTimestamp());
        String sortStartParam = "";
        if (sortStart != null && !sortStart.isEmpty()) {
            sortStartParam = "&sortStart=" + sortStart;
        }
        long cacheParam = currentReqTrace + 1;
        String callbackId = String.valueOf(currentReqTrace);

        // 2. 请求快讯数量
        String countUrl = String.format(COUNT_URL_TEMPLATE,
                sortStartParam,
                currentReqTrace,
                cacheParam,
                callbackId);
        log.info("请求快讯数量URL: {}", countUrl);
        String jsonpResponse = Jsoup.connect(countUrl)
                .ignoreContentType(true)
                .execute()
                .body();
        String jsonResponse = JsonUtils.extractJsonFromJsonp(jsonpResponse);
        JsonNode rootNode = new ObjectMapper().readTree(jsonResponse);
        int count = rootNode.path("data").path("count").asInt();
        log.info("快讯数量: {}", count);

        currentReqTrace = System.currentTimeMillis();
        // 3. 请求快讯内容
        int pageSize = count > 0 ? count : 1;
        String newsUrl = String.format(NEWS_URL_TEMPLATE, pageSize, currentReqTrace);
        log.info("请求快讯内容URL: {}", newsUrl);
        String response = Jsoup.connect(newsUrl)
                .ignoreContentType(true)
                .execute()
                .body();
        List<StockNews> newsList = parseResponse(response);
        log.info("快讯内容数量: {}", newsList.size());
        return newsList;
    }

    private List<StockNews> parseResponse(String jsonResponse) throws IOException {
        List<StockNews> newsList = new ArrayList<>();
        JsonNode rootNode = new ObjectMapper().readTree(jsonResponse);
        JsonNode dataNode = rootNode.path("data");
        JsonNode newsListNode = dataNode.path("fastNewsList");
        if (newsListNode.isArray()) {
            for (JsonNode newsNode : newsListNode) {
                StockNews news = new StockNews();
                news.setUrl(URL_ + newsNode.path("code").asText() + END);
                news.setPublishTime(newsNode.path("showTime").asText());
                news.setTitle(newsNode.path("title").asText());
                newsList.add(news);
            }
        }
        return newsList;
    }

    public long getTodayMidnightTimestamp() {
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 设置时间为00:00:00
        LocalDateTime midnight = today.atStartOfDay();

        // 转换为北京时区的ZonedDateTime
        ZoneId beijingZone = ZoneId.of("Asia/Shanghai");
        ZonedDateTime beijingMidnight = midnight.atZone(beijingZone);

        // 获取时间戳（微秒） = 毫秒 * 1000
        return beijingMidnight.toInstant().toEpochMilli() * 1000;
    }

    @Override
    protected String getApiUrl() {
        return null;
    }
}